package com.yikaiye.android.yikaiye.ui.activity.home;

import android.graphics.Paint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.base.BaseActivity;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.ActivitySerachBinding;
import com.yikaiye.android.yikaiye.http.ApiFactory;
import com.yikaiye.android.yikaiye.model.ProductModel;
import com.yikaiye.android.yikaiye.ui.activity.home.viewmodel.SearchViewModel;
import com.yikaiye.android.yikaiye.ui.adapter.EmptyRecyclerCommonAdapter;
import com.yikaiye.android.yikaiye.ui.adapter.RecyclerViewHolder;
import com.yikaiye.android.yikaiye.utils.CommonUtil;
import com.yikaiye.android.yikaiye.utils.JumpIntent;
import com.yikaiye.android.yikaiye.utils.SearchHistoryUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 搜索
 */
public class SearchActivity extends BaseActivity<ActivitySerachBinding, SearchViewModel> {

    private boolean isRecommend;
    private List<ProductModel> productData = new ArrayList<>();
    private EmptyRecyclerCommonAdapter<ProductModel> productAdapter;

    @Override
    protected SearchViewModel bindModel() {
        return getViewModel(this, SearchViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.search_text));
        initHistory();
    }

    @Override
    protected void initClick() {
        viewModel.onDelayClick(binding.ivClear, o -> {
            SearchHistoryUtil.cleanHistory();
            initHistory();
        });
        binding.etSearchContent.setOnEditorActionListener((textView, i, keyEvent) -> {
            CommonUtil.closeKeyboard(SearchActivity.this);
            String keyWord = binding.etSearchContent.getText().toString();
            if (!TextUtils.isEmpty(keyWord)) {
                SearchHistoryUtil.saveKeyWord(keyWord);
                binding.llSearchHistory.setVisibility(View.GONE);
                search(keyWord, false);
            }
            return true;
        });

        viewModel.onDelayClick(binding.ivClearKeywords, o -> {
            binding.llProductList.setVisibility(View.GONE);
            binding.llSearchHistory.setVisibility(View.VISIBLE);
            binding.etSearchContent.setText("");
            initHistory();
        });

        binding.etSearchContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (TextUtils.isEmpty(charSequence.toString())) {
                    binding.llProductList.setVisibility(View.GONE);
                    binding.llSearchHistory.setVisibility(View.VISIBLE);
                }
                binding.ivClearKeywords.setVisibility(charSequence.toString().isEmpty() ? View.GONE : View.VISIBLE);
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });

        viewModel.productData.observe(this, productModels -> {
            binding.llSearchHistory.setVisibility(View.GONE);
            if (null != productModels) {
                if (productModels.isEmpty()) {
                    binding.tvProductTitle.setVisibility(View.VISIBLE);
                    binding.llNoData.setVisibility(View.VISIBLE);
                    search("", true);
                } else {
                    binding.tvProductTitle.setVisibility(isRecommend ? View.VISIBLE : View.GONE);
                    binding.llNoData.setVisibility(isRecommend ? View.VISIBLE : View.GONE);
                    productData = productModels;
                    productAdapter.onRefresh(productData);
                }
                binding.llProductList.setVisibility(View.VISIBLE);
            }
            dismissLoadingDialog();
        });
        viewModel.mErrorData.observe(this, s -> dismissLoadingDialog());

        productAdapter.setOnItemClickListener((parent, view, position) -> {
            Bundle bundle = new Bundle();
            bundle.putString(Constant.ID_KEY, productData.get(position).getId());
            JumpIntent.jump(SearchActivity.this, ProductDetailsActivity.class, bundle);
        });
    }

    /**
     * 搜索历史
     */
    private void initHistory() {
        final List<String> data = SearchHistoryUtil.getHistory();
        binding.llSearchHistory.setVisibility(View.VISIBLE);
        ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(10, 20, 20, 20);
        binding.layoutHistory.removeAllViews();
        for (String s : data) {
            if (TextUtils.isEmpty(s)) {
                return;
            }
            //添加分类块
            View paramItemView = getLayoutInflater().inflate(R.layout.item_search_history_layout, null);
            TextView tvContent = paramItemView.findViewById(R.id.tv_content);
            tvContent.setText(s);
            binding.layoutHistory.addView(paramItemView, layoutParams);
            tvContent.setOnClickListener(v -> {
                SearchHistoryUtil.saveKeyWord(s);
                binding.etSearchContent.setText(s);
                binding.etSearchContent.setSelection(binding.etSearchContent.getText().toString().length());
                search(s, false);
            });
        }
    }

    @Override
    public void initCtrl() {
        productAdapter = new EmptyRecyclerCommonAdapter<ProductModel>(context, R.layout.item_product_layout_line, productData) {
            @Override
            public void convert(RecyclerViewHolder holder, ProductModel item, int position) {
                holder.setText(R.id.tv_title, item.getTitle());
                holder.setText(R.id.tv_des, item.getSlogan());
                holder.setText(R.id.tv_price, getString(R.string.price, item.getMinPrice()));
                TextView tvOriginalPrice = holder.getView(R.id.tv_line_price);
                tvOriginalPrice.setVisibility(View.VISIBLE);
                tvOriginalPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                tvOriginalPrice.setText(getString(R.string.price, item.getMaxPrice()));
                Glide.with(context).load(ApiFactory.BASE_IMAGE_URL + item.getAppBanner())
                        .placeholder(R.mipmap.default_image).error(R.mipmap.default_image)
                        .into((ImageView) holder.getView(R.id.iv_product_img));
            }
        };
        binding.recyclerView.setAdapter(productAdapter);
    }

    /**
     * 搜索
     *
     * @param keyWord     关键字
     * @param isRecommend 是否是推荐产品
     */
    private void search(String keyWord, boolean isRecommend) {
        showLoadingDialog();
        this.isRecommend = isRecommend;
        viewModel.getProductList(keyWord, isRecommend);
    }
}